#' @title read heatmap data from www.creprice.cn
#' @description This function will help you to get data quickly from creprice website.
#' @param city_code character indicating the code of city where would you like to fetch data.The default value is 'bj'.
#' @return SpatialPointsDataFrame Object
#' @export read.heatmap
#' @examples
#' heat.qd<-read.heatmap('qd')
#' plot(heat.qd)
read.heatmap<-function(city_code='bj')
{
  if(is.null(city_code)|class(city_code)!='character') {
    stop('city code is invalid!')
  }
  library(RCurl)
  library(XML)
  require(stringr)
  #   url<-'http://www.creprice.cn/market/heatmap/city/bt/flag/1/proptype/11.html'
      url2<-paste0('http://www.creprice.cn/market/heatmapLoad/city/',city_code,
                   '/flag/1/proptype/11.html')
      myheader=c("User-Agent"="Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",
                 "Accept"="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                 "Accept-Language"="en-us",
                 "Connection"="keep-alive",
                 "Accept-Charset"="GB2312,utf-8;q=0.7,*;q=0.7"
      )
      webpage  <-tryCatch(getURLContent(url2,httpheader=myheader,.encoding="utf-8"),
                          error = function(e) {
                              getURLContent(url2,httpheader=myheader,
                                            .encoding="utf-8", timeout = 200) })
  heatmap.data<-
    str_extract(string = webpage,pattern = '\"data\":\\[\\{(.+)\\]')
  heatmap.data<-str_replace(heatmap.data,pattern = '\"data\":',replacement = '')
  list1<-rjson::fromJSON(heatmap.data)
  df1<-matrix(unlist(list1),byrow = T,ncol=4)
  colnames(df1)<-c('lng','lat','count','radius')
  df1<-data.frame(lng=as.numeric(df1[,'lng']),
                  lat=as.numeric(df1[,'lat']),
                  count=as.numeric(df1[,'count']),
                  radius=as.numeric(df1[,'radius'])
  )
  require(maptools)
  coordinates(df1)<-~lng+lat
  df1
}

